from django.db import models
from django.conf import settings
from django.shortcuts import reverse
from django.contrib.auth import get_user_model
from django.utils.html import strip_tags
import markdown
import re
from uuslug import slugify

import jieba
import jieba.analyse

# Create your models here.

User = get_user_model()

class Category(models.Model):
    name = models.CharField(verbose_name="文章分类",max_length=20)
    slug = models.SlugField(unique=True,editable=False)
    description = models.TextField(verbose_name="分类描述",default=settings.SITE_DESCRIPTION,
                                   help_text="用来作为SEO中description,长度参考SEO标准")
    keywords = models.TextField(verbose_name="关键字",default=settings.SITE_KEYWORDS,
                                help_text="用来作为SEO中keywords,长度参考SEO标准")
    parent =  models.ForeignKey('self', related_name='parent_category',
                                  blank=True, null=True, verbose_name="上级分类", on_delete=models.CASCADE)
    is_tab = models.BooleanField(verbose_name="是否导航栏",default=False)

    class Meta:
        verbose_name = "文章分类"
        verbose_name_plural = verbose_name
        db_table = "blog_category"

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('blog:category', kwargs={'slug':self.slug})

    def get_article_list(self):
        return Article.objects.filter(category=self)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(Category, self).save(*args, **kwargs)


class Tag(models.Model):
    name = models.CharField(verbose_name="文章标签",max_length=20)
    slug = models.SlugField(unique=True,verbose_name="标签url标识",editable=False)
    description = models.TextField(verbose_name="标签描述",default=settings.SITE_DESCRIPTION,
                                   help_text="用来作为SEO中description,长度参考SEO标准")

    class Meta:
        verbose_name =  "文章标签"
        verbose_name_plural = verbose_name
        ordering = ['id']
        db_table = "blog_tag"

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(Tag, self).save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse('blog:tag',kwargs={'tag':self.slug})

    def get_article_list(self):
        return Article.objects.filter(tag=self)


class Keyword(models.Model):
    name = models.CharField(verbose_name="文章关键字",max_length=20)

    class Meta:
        verbose_name = "文章关键字"
        verbose_name_plural =verbose_name
        ordering = ['name']

    def __str__(self):
        return self.name

class Article(models.Model):
    title = models.CharField(verbose_name="博文标题",max_length=280)
    author = models.ForeignKey(User,on_delete=models.CASCADE,verbose_name="博文作者",default=1)
    body = models.TextField(verbose_name='文章内容')
    abstract = models.TextField(null=True,verbose_name="文章摘要")
    thumbnail = models.ImageField(upload_to="images/article/%y/%m/%d/",default="images/default_thumbnail.png")
    slug = models.SlugField(unique=True,editable=False)
    categroy = models.ForeignKey('Category',on_delete=models.CASCADE,verbose_name="文章分类")
    tags = models.ManyToManyField("Tag",verbose_name="文章标签")
    keywords = models.ManyToManyField("Keyword",verbose_name="文章关键字",
                                      help_text="文章关键词，用来作为SEO中keywords，最好使用长尾词，3-4个足够")
    views = models.IntegerField(verbose_name="阅读量",default=0)
    love = models.IntegerField(verbose_name="喜欢量",default=0)
    create_time = models.DateTimeField(verbose_name="创建时间",auto_now_add=True)
    update_time = models.DateTimeField(verbose_name="更新时间",auto_now=True)

    class Meta:
        verbose_name = "博文"
        verbose_name_plural = verbose_name
        ordering =  ['-create_time']
        db_table = "blog_article"

    def __str__(self):
        return self.title[:20]

    def get_absolute_url(self):
        return reverse("blog:article",kwargs={"slug":self.slug})

    def body_to_markdown(self):
        context = markdown.markdown(self.body, extensions=[
                'markdown.extensions.extra',
                'markdown.extensions.codehilite',
            ])
        return context

    def update_views(self):
        self.views +=1
        self.save(update_fields=["views"])

    # 重写保存的方法
    def save(self, *args, **kwargs):
        self.slug = slugify(self.title[:20])

        if not  self.abstract:
            # 如果没有摘要，则从body中取一部分
            # 实例化md，用于渲染body文本
            md = markdown.Markdown(extensions=[
                'markdown.extensions.extra',
                'markdown.extensions.codehilite',
            ])
            # 将md文本渲染成html
            # strip_tags 去掉html文本的全部html标签
            # 摘取body前54个给excerpt
            self.abstract = strip_tags(md.convert(self.body))[:54]

        super(Article, self).save(*args, **kwargs)

    def get_pre(self):
        return Article.objects.filter(id__lt=self.id).order_by('-id').first()

    def get_next(self):
        return Article.objects.filter(id__gt=self.id).order_by('id').first()

#公告
class Activate(models.Model):
    text = models.TextField(verbose_name="公告",null=True)
    is_active = models.BooleanField(verbose_name="是否开启",default=False)
    create_time = models.DateTimeField(verbose_name="创建日期",auto_created=True)

    class Meta:
        verbose_name  = "公告"
        verbose_name_plural = verbose_name
        ordering = ["-create_time"]
        db_table = "blog_activate"

    def __str__(self):
        return self.text[:10]


# 幻灯片
class Carousel(models.Model):
    number = models.IntegerField('编号', help_text='编号决定图片播放的顺序，图片不要多于5张')
    title = models.CharField('标题', max_length=20, blank=True, null=True, help_text='标题可以为空')
    content = models.CharField('描述', max_length=80)
    image = models.ImageField(upload_to="images/carousel/%y/%m/%d/",default="images/default_carousel.png")
    article = models.ForeignKey("Article",on_delete=models.SET_NULL,null=True,blank=True)

    class Meta:
        verbose_name = '图片轮播'
        verbose_name_plural = verbose_name
        # 编号越小越靠前，添加的时间约晚约靠前
        ordering = ['number', '-id']
        db_table = "blog_carousel"

    def __str__(self):
        return self.content[:25]


# 友情链接表
class FriendLink(models.Model):
    name = models.CharField('网站名称', max_length=50)
    description = models.CharField('网站描述', max_length=100, blank=True)
    link = models.URLField('友链地址', help_text='请填写http或https开头的完整形式地址')
    logo = models.URLField('网站LOGO', help_text='请填写http或https开头的完整形式地址', blank=True)
    create_date = models.DateTimeField('创建时间', auto_now_add=True)
    is_active = models.BooleanField('是否有效', default=True)
    is_show = models.BooleanField('是否首页展示', default=False)

    class Meta:
        verbose_name = '友情链接'
        verbose_name_plural = verbose_name
        ordering = ['create_date']
        db_table = "blog_friendlink"

    def __str__(self):
        return self.name

    def get_home_url(self):
        """提取友链的主页"""
        u = re.findall(r'(http|https://.*?)/.*?', self.link)
        home_url = u[0] if u else self.link
        return home_url

    def active_to_false(self):
        self.is_active=False
        self.save(update_fields=['is_active'])

    def show_to_false(self):
        self.is_show = True
        self.save(update_fields=['is_show'])


